import { createRouter, createWebHistory } from 'vue-router'
import HomepageView from '../views/HomepageView.vue'
import ClassManagement from '../views/ClassManagement.vue'
import QuestionBank from '../views/QuestionBank.vue'
import Login from '../views/Login.vue'
import Register from '../views/Register.vue'
import { isAuthenticated } from '../utils/token'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/login',
      name: 'login',
      component: Login,
      meta: { requiresAuth: false }
    },
    {
      path: '/register',
      name: 'register',
      component: Register,
      meta: { requiresAuth: false }
    },
    {
      path: '/',
      name: 'home',
      component: HomepageView,
      meta: { requiresAuth: true }
    },
    {
      path: '/class/:id',
      name: 'class-management',
      component: ClassManagement,
      props: true,
      meta: { requiresAuth: true }
    },
    {
      path: '/question-bank',
      name: 'question-bank',
      component: QuestionBank,
      meta: { requiresAuth: true }
    }
  ],
})

// 路由守卫：检测 JWT 令牌
router.beforeEach((to, from, next) => {
  const isLoggedIn = isAuthenticated()
  
  // 如果目标路由需要认证
  if (to.meta.requiresAuth) {
    if (isLoggedIn) {
      // 已登录，允许访问
      next()
    } else {
      // 未登录，跳转到登录页
      next({ name: 'login', query: { redirect: to.fullPath } })
    }
  } else {
    // 不需要认证的路由
    if ((to.name === 'login' || to.name === 'register') && isLoggedIn) {
      // 已登录用户访问登录/注册页，重定向到首页
      next({ name: 'home' })
    } else {
      next()
    }
  }
})

export default router